import Cookies from 'js-cookie'
import { constantRouterMap } from '@/router'
import ansycRouterMap from '@/router/ansycRouter'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  routers: constantRouterMap,
  navRouters: ansycRouterMap,
  currentPathArr: [],
  isKeepAlive: false,
  refreshRouterName: '',
  tagNavList: [
    {
      label: '首页',
      path: '/',
      name: '首页',
      lastTime: 0
    }
  ]
}
const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  // 顶部菜单
  SET_ROUTERS: (state, routers) => {
    state.routers = constantRouterMap.concat(routers)
  },
  // 左侧菜单
  SET_SIDE_PATH: (state, currentPathArr) => {
    state.currentPathArr = currentPathArr
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  SET_REFREASH_ROUTER_NAME: (state, name) => {
    state.refreshRouterName = name
  },
  SET_IS_KEEP_LIVE(state, type) {
    state.isKeepAlive = type
  },
  UPDATE_TAG_NAV_LIST(state, data) {
    const isIn = state.tagNavList.some(v => v.name === data.name)
    if (!isIn && data.name !== '登录') {
      state.tagNavList.push(data)
    }
  },
  DELETE_TAG_NAV_LIST(state, data) {
    const index = state.tagNavList.findIndex(v => v.name === data.name)
    state.tagNavList.splice(index, 1)
  },
  CLEAR_ALL_TAG_NAV_LIST(state, data) {
    state.tagNavList = [
      {
        label: '首页',
        path: '/',
        name: '首页',
        lastTime: 0
      }
    ]
  }

}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  GenerateRoutes({ commit }, data) {
    return new Promise(resolve => {
      commit('SET_ROUTERS', ansycRouterMap)
      resolve()
    })
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  updateTagNavList({ commit }, dataObj) {
    commit('UPDATE_TAG_NAV_LIST', dataObj)
  },
  setRefreshRouterName({ commit }, name) {
    commit('SET_REFREASH_ROUTER_NAME', name)
  },
  setIsKeepAlive({ commit }, type) {
    commit('SET_IS_KEEP_LIVE', type)
  },
  deleteTagNavList({ commit }, data) {
    commit('DELETE_TAG_NAV_LIST', data)
  },
  closeAllTagNavList({ commit }, type) {
    commit('CLEAR_ALL_TAG_NAV_LIST')
  },
  pushOrUpdateTagNavList({ commit }, type) {

  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
